/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-09-18 09:49:36
 * @filename : static/logic/nmm/src/views/userProfile.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module) {

    require("{component}slider/zepto.slider.css");
    require("{component}slider/zepto.sliderDialog.css");
    require("{component}dialog/zepto.dialog.css");
    require('{component}promptTip/promptTip.css');
      
    var userProfileView,nav='userProfile',userObj,backUrl,mId='userProfile',
        panel = require('{component}panel/zepto.panel'),
        slider = require('{component}slider/zepto.slider'),
        sliderDialog = require('{component}slider/zepto.sliderDialog'),
        dialog = require('{component}dialog/zepto.dialog'),
        promptTip = require('{component}promptTip/promptTip'),
        imglazyload = require('{component}imglazyload/zepto.imglazyload');
    
    userProfileView = Backbone.View.extend({
         
        el: 'body',
         
        template: '',
        templateA: '',
        templateN: '',
        templateS: '',
        templateD: '',
        templateSD: '',
        
        initialize: function () {
            this.template   = require('{view}userProfile.tpl');
            this.templateS  = require('{view}sliderLi.tpl');
            this.templateD  = require('{view}userProfileDetail.tpl');
            this.templateSD  = require('{view}sliderDialog.tpl');
            this.templateN  = require('{view}userNav.tpl');
            this.templateA  = require('{view}userProfileAbout.tpl');
        },
        
        render: function (obj) {
            var tthis = this;
            if (!share.checkPermission(true)){return;};
            if (typeof(obj.val) == 'undefined') {
                window.history.go(-1);
            }  

            if ($('#'+mId).length < 1) {
                $('body').append(_.template(this.template, lang));
                if ($('#userNav').length < 1) {
                    $('body').append(_.template(this.templateN, lang));
                    panel.init();
                    $('#userNav').imglazyload({startY : 0,endY: $(window).height(),sW:50,sH:50});
                }
                this.bindEvt();
            } else {
                $('#'+mId).css('display','block');
            }
            
            var arr = obj.val.split('&&'); 
            backUrl = arr[2];
            userObj = JSON.parse(this.getCacheUserInfo(arr[0]));
            if (userObj == undefined) {
                $('#'+mId).find('.head').find('span').eq(1).html(arr[1]);
                this.getAjaxUserInfo(arr);
            } else {
                this.ajaxAfterDo(); 
            }

            window.scroll(0,0);
            share.tabSwitch($('#'+mId),0);
            this.panel();

            $('#'+mId).find('.inputMsg').val('');  
        },
          
        bindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            dom.find('.back').on('tap',function(e){
                if (backUrl == undefined) {
                  window.history.go(-1);
                } else {
                  window.location.href = '#'+backUrl+'/whole';
                }
                tthis.sliderMoveDom(); 
            });

            dom.find('.tabTitle').find('li').on('tap',function(){
                var index = $(this).index();
                share.tabSwitch(dom,index);  
            });

            dom.find('.sendButton').on('tap',function(){
                var input = dom.find('.inputGroup').find('input'),
                    val = input.val();

                input.blur();

                if ($.trim(val) !== '') {
                    if ($(this).attr('ajax') != 1) {
                        tthis.ajaxSendMessage(this, val);
                    }
                } else {
                    promptTip.show({type:'error',text:'You can’t send a blank message.', dom:dom.find('.promptTip'),time:2000});
                }
                
            });

            dom.find('#slider').on('tap',function(){
                tthis.sliderDialogDom(); 
            });

            dom.find('.btn-frvorites').on('tap',function(){
                var url='',str = $.trim($(this).html());
                if (str == 'A FAVORITE') {
                    url = 'remove_favor'; 
                    $(this).addClass('buttonLoading').html('Removing');
                } else if (str == 'FAVORITE') {
                    url = 'add_favor';
                    $(this).addClass('buttonLoading').html('Add');
                }
                if ($(this).attr('ajax') != 1 && url !== '') {
                    tthis.ajaxAddFavor(this,url);
                }
            });

            dom.find('.btn-freewink').on('tap',function(){ 
                if ($(this).attr('ajax') != 1 && userObj.status.isWinked !== 1) {
                    $(this).addClass('buttonLoading').html('Sending');
                    tthis.ajaxSendWink(this);
                }
            });
        
        },
         
        loadUserInfo : function() {
            var dom = $('#'+mId);
            dom.find('.head').find('span').eq(1).html(userObj.account.username);
            
            dom.find('#slider_box').find('.slider_item_des_name').find('.s1').html(userObj.account.username);
            
            if (userObj.status.income_verify) {
                //dom.find('#slider_box').find('.slider_item_des_name').find('.s2').addClass('diamond');
            }

            if (!parseInt(userObj.status.isGuest)) {
                dom.find('#slider_box').find('.slider_item_des_name').find('.s3').addClass('gold').css('margin','0px');
            }

            var lsName = userObj.account.city;

            if (userObj.account.city == null) {
                lsName=userObj.account.state_name; 
            }

            dom.find('#slider_box').find('.slider_item_des_age').find('span').eq(0).html(userObj.account.age);
            dom.find('#slider_box').find('.slider_item_des_age').find('span').eq(3).html(lsName);
            dom.find('#slider_box').find('.slider_item_des_age').find('span').eq(4).html(userObj.account.country_name);
 
            this.changeWinkedUI(userObj.status.isWinked);
            this.changeFrvorUI(userObj.status.isFavorite);
        }, 

        changeFrvorUI : function(bool) {
            var dom = $('#'+mId);
            if (bool) {
                dom.find('.btn-frvorites').html('A FAVORITE').addClass('btn-favotrited');
            } else {
                dom.find('.btn-frvorites').html('FAVORITE').removeClass('btn-favotrited');
            }
        },

        changeWinkedUI : function(bool) {
            var dom = $('#'+mId);
            if (bool) {
               dom.find('.btn-freewink').html('WINKED').addClass('btn-freewinked');
            } else {
               dom.find('.btn-freewink').html('FREE WINK').removeClass('btn-freewinked');
            }
        },

        getCacheUserInfo : function(userId) {
            return share.getStorage(userId); 
        },

        ajaxSendMessage : function(that, text) {
            var tthis = this,dom = $('#'+mId);
                $(that).attr('ajax',1); 
            var obj = {
                url : seajs.data.vars.apiAccessUrl+'send_email',
                type : 'POST',
                data : {prof_id:userObj.account.usr_id, text: text},
                success : function(data) {
                    $(that).attr('ajax',0);
                    if (data.results == 1) {
                        $('.inputGroup').find('input').val('');
                        promptTip.show({type:'success',text:'Message successfully sent.',dom:$('#'+mId).find('.promptTip'),time:2000});                         
                    } else {
                        if (data.errcode == 119) {
                            promptTip.show({type:'btn',btnText:'Upgrade',text:'Upgrade now to contact this member today.',dom:$('#'+mId).find('.promptTip'),callback:function(){window.location.href = '#upgrade/whole';}});
                        } else {
                            promptTip.show({type:'error',text:'Message sent error!', dom:dom.find('.promptTip'),time:2000});
                        }
                    }
                }, 
                error : function(xhr, errorType, error) {
                    share.error('alert','http request failed!'); 
                }
            };
            $.ajax(share.ajaxControl(obj));
        },

        ajaxSendWink : function(that) {
            var tthis = this,dom = $('#'+mId);
                $(that).attr('ajax',1); 
            var obj = {
                   url : seajs.data.vars.apiAccessUrl+'send_wink',
                   type : 'POST',
                   data : {prof_id:userObj.account.usr_id},
                   success : function(data) {
                        $(that).attr('ajax',0).html('WINKED').removeClass('buttonLoading');
                        if (data.results == 1) {
                            userObj.status.isWinked = 1;
                            share.cacheUserInfo(userObj.account.usr_id,userObj);
                            tthis.changeWinkedUI(1); 
                        }
                   }, 
                   error : function(xhr, errorType, error) {
                       share.error('alert','http request failed!'); 
                   }
			    };
            $.ajax(share.ajaxControl(obj));
        },

        ajaxAddFavor : function(that,url) {
             $(that).attr('ajax',1); 
             var tthis = this,
                  obj = {
                   url : seajs.data.vars.apiAccessUrl+url,
                   type : 'POST',
                   data : {prof_id:userObj.account.usr_id},
                   success : function(data) {
                        $(that).attr('ajax',0); 
                        if (data.errcode != 10) {
                            var type
                            if (url == 'add_favor') {
                                $(that).removeClass('buttonLoading');
                                userObj.status.isFavorite = 1;  
                                type = 'add';
                            } else {
                                $(that).removeClass('buttonLoading');
                                userObj.status.isFavorite = 0;
                                type = 'remove';  
                            }
                    
                            tthis.changeFrvorUI(userObj.status.isFavorite);
                            share.cacheUserInfo(userObj.account.usr_id,userObj);
                        }         
                   }, 
                   error : function(xhr, errorType, error) {
                       share.error('alert','http request failed!'); 
                   }
			    };
             
             $.ajax(share.ajaxControl(obj));
        },
        
        getAjaxUserInfo : function(arr) {
            share.pageLoad(true,$('body'));
            var tthis = this,
                data = {
                   username : arr[1],
                   prof_id : arr[0] 
                },
                obj = {
                   url : seajs.data.vars.apiAccessUrl+'user_profile',
                   type : 'POST',
                   data : data,
                   success : function(data) {
                       share.pageLoad(false,$('body'));
                       if (data.errcode == 121) {
                           alert(data.errmsg);
                           if (backUrl == undefined) {
                               window.history.go(-1);
                           } else {
                               window.location.href = '#'+backUrl+'/whole';
                           }
                       } else {
                           share.cacheUserInfo(arr[0],data);
                           userObj = JSON.parse(tthis.getCacheUserInfo(arr[0]));
                           //console.log(userObj);
                           tthis.ajaxAfterDo(); 
                       }  
                   }, 
                   error : function(xhr, errorType, error) {
                       share.error('alert','http request failed!'); 
                   }
			    };
              $.ajax(share.ajaxControl(obj));
        },
   
        ajaxAfterDo : function() {
              this.loadUserInfo(); 
              this.sliderLoadDom();
              this.userLoadAboutDom(); 
        },

        sliderDialogDom : function() {
            var loadImg = seajs.data.vars.resourceUrl+'img/blank.png',
                str = $('#'+mId).find('.slider-item-num').html();
            if (str !== '') { 
                var index = str.split('/')[0] - 1;
                if ($('#sliderDialog').length > 0){$('#sliderDialog').remove()};
                $('body').append(_.template(this.templateSD, {arr:userObj.pictures,loadImg:loadImg}));
                $('#sliderDialog').sliderDialog({index:index});
                $('#sliderDialog').imglazyload({
                    startY : 0,
                    endY: $(window).height(),
                    transform : false,
                    screen : false 
                });
            }
        },

        userLoadAboutDom : function() {
            //装载用户其他数据,可以Tpl整体替换
            var userAboutObj    = userObj.about;
            userAboutObj.relation = share.showCheckboxLabel('ms_relation', userObj.about.looking_for);

            $('#'+mId).find('.tabContent').eq(0).html(_.template(this.templateA, { user: userAboutObj }));

            var userDetailObj = {};
            for (var item in userObj.detail) {
                for (var subItem in userObj.detail[item]) {
                    var tmpSubItem = '';
                    switch(subItem) {
                        case 'political' :
                            tmpSubItem = 'political_beliefs';
                            break;
                        case 'eyes_color': 
                            tmpSubItem = 'eyes';
                            break;
                        case 'hair_color': 
                            tmpSubItem = 'hair';
                            break;
                        case 'body_type': 
                            tmpSubItem = 'body';
                            break;
                        case 'income': 
                            tmpSubItem = 'type';
                            break;
                        case 'smoking': 
                            tmpSubItem = 'smoker';
                            break;
                        case 'drinking': 
                            tmpSubItem = 'drinker';
                            break;
                        case 'have_pets': 
                            tmpSubItem = 'pets';
                            break;
                    }
                    var key = tmpSubItem || subItem;

                    var itemObj = new Backbone.Collection(share.getLocalStorage("ms_" + key));
                    if (itemObj.length > 0) {
                        var subItemModel = itemObj.where({ value: userObj.detail[item][subItem] });
                        if (subItemModel.length > 0) {
                            userDetailObj[subItem] = subItemModel[0].get("label");
                        } else {
                            userDetailObj[subItem] = 'Please ask me';
                        }
                    }
                }
            }
            $('#'+mId).find('.tabContent').eq(1).html(_.template(this.templateD,{user: userDetailObj}));
        },

        sliderLoadDom : function() {
            var tthis  = this,
                loadImg = seajs.data.vars.resourceUrl+'img/blank.png',
                noImg = seajs.data.vars.resourceUrl+'img/default'+userObj.account.gender+'.png';

            this.sliderMoveDom();
 
            if (userObj.pictures.length > 0) {
                $('#slider').find('ul').append(_.template(this.templateS,{arr:userObj.pictures,loadImg:loadImg}));
                $('#slider ul').slider({
                     sliderInit : function(data){tthis.sliderAfter(data)},
                     sliderAfter : function(data) {tthis.sliderAfter(data)} 
                });
            } else {
                $('#slider').find('ul').append(_.template(this.templateS,{arr:[{'picture':noImg}],loadImg:loadImg}));
                $('#slider_box').find('.slider-item-num').html('');
            }
             
            $('#'+mId).imglazyload({
                startY : 0,
                endY: $(window).height(), 
                sW: $('#slider').width(), 
                sH: $('#slider').height()
            });
        },

        sliderMoveDom : function() {
            $('#slider ul').off('.slider').find('li').remove();
            $('#slider_box').find('.slider-pre').off('.slider').off('.slider');
            $('#slider_box').find('.slider-next').off('.slider').off('.slider');
        },
 
        sliderAfter : function(data) {
            $('#slider_box').find('.slider-item-num').html(data.index+1+"/"+data.sliderNum);
        },
             
        panel : function() {
            panel.run({
                navName : nav,
                rootDom : $('#'+mId),
                contentDom : $('#'+mId).find('.body_all')
            });
        },

    });

    module.exports = userProfileView;
});
